#include "util.h"

#include <stdio.h>
#include <sys/socket.h>

int recv_line(int sock, char *buf, int size)
{
    int i = 0;
    char c = '\0';
    int n;

    while ((i < size - 1) && (c != '\n')) {
        n = recv(sock, &c, 1, 0);
        /* DEBUG printf("%02X\n", c); */
        if (n > 0) {
            if (c == '\r') {
                n = recv(sock, &c, 1, MSG_PEEK);
                /* DEBUG printf("%02X\n", c); */
                if ((n > 0) && (c == '\n'))
                    recv(sock, &c, 1, 0);
                else
                    c = '\n';
            }
            buf[i] = c;
            i++;
        } else
            c = '\n';
    }
    buf[i] = '\0';

    return (i);
}

int send_all(int sock, const void *buf, int len)
{
    int ret = 0;
    int off = 0;

redo:
    ret = send(sock, buf + off, len - off, 0);
    if (ret <= 0)
        return ret;

    off += ret;
    if (off < len)
        goto redo;

    return off;
}

void send_file(int sock, FILE *fp)
{
    char buf[1024];
    int len;

    len = fread(buf, sizeof(*buf), sizeof(buf), fp);
    while (!feof(fp)) {
        send_all(sock, buf, len);
        len = fread(buf, sizeof(*buf), sizeof(buf), fp);
    }
}
